﻿package com.taihua_tech.basic.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.taihua_tech.basic.dao.NoteDao;
import com.taihua_tech.basic.dao.ShareDao;
import com.taihua_tech.basic.entity.Note;
import com.taihua_tech.basic.entity.Share;
import com.taihua_tech.basic.util.NoteResult;
import com.taihua_tech.basic.util.NoteUtil;
 

@Service("shareService")
@Transactional
public class ShareServiceImpl implements ShareService{
	@Resource
	private ShareDao shareDao;
	@Resource
	private NoteDao noteDao;
	
	public NoteResult shareNote(String noteId) {
		NoteResult result = new NoteResult();
		//检查该笔记是否分享过
		Share hasShare = shareDao.findByNoteId(noteId);
		if(hasShare!=null){
			result.setStatus(2);
			result.setMsg("该笔记已分享过");
			return result;
		}
		//未分享过执行分享逻辑
		Note note = noteDao.findById(noteId);
		if(note != null){//分享处理
			Share share = new Share();
			share.setCn_note_id(noteId);//设置笔记ID
			share.setCn_share_title(
				note.getCn_note_title());//设置分享标题
			share.setCn_share_body(
				note.getCn_note_body());//设置分享内容
			String shareId = NoteUtil.createId();
			share.setCn_share_id(shareId);//设置分享ID
			shareDao.save(share);//插入
			//TODO 将cn_note中该笔记的type_id设置成分享Code 1：未分享 2：表示分享
			result.setStatus(0);
			result.setMsg("分享笔记成功");
		}else{
			result.setStatus(1);
			result.setMsg("该分享笔记已不存在");
		}
		return result;
	}

	public NoteResult shareSearch(String keyword) {
		String title = "%";
		if(keyword!=null && !"".equals(keyword)){
			title = "%"+keyword.trim()+"%";
		}
		List<Share> list = 
			shareDao.findLikeTitle(title);
		NoteResult result = new NoteResult();
		result.setStatus(0);
		result.setMsg("搜索完成");
		result.setData(list);
		return result;
	}

	public NoteResult loadShare(String shareId) {
		Share share = shareDao.findById(shareId);
		NoteResult result = new NoteResult();
		result.setStatus(0);
		result.setMsg("加载笔记成功");
		result.setData(share);
		return result;
	}

}
